<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import request from '@/utils/request';
import { Service as IconService } from '@element-plus/icons-vue';

// 定义类型
interface Course {
  id: number;
  name: string;
  progress: number; // 课程进度百分比
}

interface ClassGroup {
  id: number;
  name: string;
}

interface UserStats {
  totalCourses: number;
  completedCourses: number;
}

interface Analytics {
  attendance: number; // 出勤率
  diligence: number; // 学习认真度
  interaction: number; // 互动率
}

const router = useRouter();
const user = ref<any>(null);
const loading = ref(false);

// 初始化数据
const stats = reactive<UserStats>({
  totalCourses: 0,
  completedCourses: 0
});

const ongoingCourses = ref<Course[]>([]);
const classes = ref<ClassGroup[]>([]);
const groups = ref<ClassGroup[]>([]);

const analytics = reactive<Analytics>({
  attendance: 0,
  diligence: 0,
  interaction: 0
});

const colors = reactive({
  attendance: '#409EFF',
  diligence: '#67C23A',
  interaction: '#E6A23C'
});

// 获取学生信息
const getStudentInfo = () => {
  try {
    const rawInfo = localStorage.getItem('studentUserInfo')
    if (!rawInfo) {
      console.error('无登录信息')
      ElMessage.warning('请先登录')
      router.push('/login')
      return null
    }

    const userInfo = JSON.parse(rawInfo)
    if (!userInfo?.stu_id) {
      localStorage.removeItem('studentUserInfo')
      console.error('登录信息无效')
      ElMessage.warning('登录信息无效，请重新登录')
      router.push('/login')
      return null
    }

    user.value = userInfo
    return userInfo
  } catch (e) {
    console.error('学生信息获取失败:', e)
    ElMessage.error('登录信息解析失败')
    router.push('/login')
    return null
  }
}

// 获取个人主页数据
const fetchPersonalData = async () => {
  loading.value = true;
  try {
    // 获取学生信息
    const userInfo = getStudentInfo();
    if (!userInfo) return;

    try {
      // 发送请求到后端API获取仪表盘数据
      const { data } = await request.get('/api/student/dashboard/', {
        params: {
          stu_id: userInfo.stu_id,
          username: userInfo.username,
          use_sql: true // 使用SQL直接查询
        }
      });

      console.log('获取到的仪表盘数据:', data);

      // 处理课程统计数据
      if (data.stats) {
        stats.totalCourses = data.stats.totalCourses || 0;
        stats.completedCourses = data.stats.completedCourses || 0;
      }

      // 处理进行中的课程
      if (data.ongoingCourses && Array.isArray(data.ongoingCourses)) {
        ongoingCourses.value = data.ongoingCourses.map(course => ({
          id: course.id,
          name: course.name || course.course_name || `课程${course.id}`,
          progress: course.progress || 0
        }));
      }

      // 处理班级和小组数据
      if (data.classes && Array.isArray(data.classes)) {
        classes.value = data.classes;
      }

      if (data.groups && Array.isArray(data.groups)) {
        groups.value = data.groups;
      }

      // 处理学情分析数据
      if (data.analytics) {
        analytics.attendance = data.analytics.attendance || 0;
        analytics.diligence = data.analytics.diligence || 0;
        analytics.interaction = data.analytics.interaction || 0;
      }

    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      ElMessage.error('获取个人数据失败，请稍后再试');
      // 加载测试数据
      loadTestData();
    }
  } finally {
    loading.value = false;
  }
};

// 加载测试数据
const loadTestData = () => {
  console.log('加载测试数据');

  // 测试数据
  stats.totalCourses = 5;
  stats.completedCourses = 2;

  ongoingCourses.value = [
    { id: 1, name: '管理信息系统', progress: 75 },
    { id: 2, name: '统计学', progress: 60 },
    { id: 3, name: '计算机网络', progress: 45 }
  ];

  classes.value = [
    { id: 1, name: '信息管理与信息系统1班' }
  ];

  groups.value = [
    { id: 1, name: '我的小组' },
  ];

  analytics.attendance = 85;
  analytics.diligence = 70;
  analytics.interaction = 65;
};

const toStudy = () => {
  router.push('/student/course/Study');
};

const courseStatus = (course) => {
  return course.progress >= 100 ? 'success' : 'primary';
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchPersonalData();
});

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
  <div v-loading="loading" class="dashboard-container">
    <div v-if="!user" class="login-required">
      <el-empty description="请先登录" />
    </div>
    <div v-else class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="user-info-card">
            <div class="user-header">
              <div>
                <h1>欢迎回来，{{ user.stu_name || user.username }}</h1>
                <div class="stats">
                  <div class="stat-item">
                    <span class="stat-label">选择课程总数</span>
                    <span class="stat-value">{{ stats.totalCourses }}</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-label">已完成课程</span>
                    <span class="stat-value">{{ stats.completedCourses }}</span>
                  </div>
                </div>
              </div>
              <div class="action-buttons">
                <el-button
                  @click="toStudy"
                  type="success"
                  size="large"
                  round
                  class="study-buddy-btn"
                >
                  <el-icon class="icon-margin"><IconService /></el-icon> 24小时学伴
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="middle-row">
        <el-col :span="12">
          <el-card class="course-list">
            <template #header>
              <span class="card-title">进行中的课程</span>
            </template>
            <div class="scroll-container">
              <div v-if="ongoingCourses.length === 0" class="empty-courses">
                <el-empty description="暂无进行中的课程" />
              </div>
              <div v-else v-for="course in ongoingCourses" :key="course.id" class="course-item">
                <div class="course-info">
                  <h4>{{ course.name }}</h4>
                  <el-progress :percentage="course.progress" :status="courseStatus(course)"/>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="class-info">
            <template #header>
              <span class="card-title">班级与小组</span>
            </template>
            <div class="group-section">
              <div class="group-item">
                <h4>所属班级</h4>
                <div v-if="classes.length === 0" class="empty-info">暂无班级信息</div>
                <router-link
                  v-for="cls in classes"
                  :key="cls.id"
                  :to="''"
                  class="group-link"
                >
                  {{ cls.name }}
                </router-link>
              </div>
              <div class="group-item">
                <h4>所属小组</h4>
                <div v-if="groups.length === 0" class="empty-info">暂无小组信息</div>
                <router-link
                  v-for="group in groups"
                  :key="group.id"
                  :to="'/student/project/team'"
                  class="group-link"
                >
                  {{ group.name }}
                </router-link>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="analysis-card">
            <template #header>
              <span class="card-title">学情分析</span>
              <span class="analysis-subtitle">* 基于所有已选课程数据的平均值</span>
            </template>
            <div class="analysis-grid">
              <div class="analysis-item">
                <div class="chart-container">
                  <div class="chart-title">出勤率</div>
                  <el-progress
                    type="dashboard"
                    :percentage="analytics.attendance"
                    :color="colors.attendance"
                  />
                </div>
              </div>
              <div class="analysis-item">
                <div class="chart-container">
                  <div class="chart-title">学习认真度</div>
                  <el-progress
                    type="dashboard"
                    :percentage="analytics.diligence"
                    :color="colors.diligence"
                  />
                </div>
              </div>
              <div class="analysis-item">
                <div class="chart-container">
                  <div class="chart-title">互动率</div>
                  <el-progress
                    type="dashboard"
                    :percentage="analytics.interaction"
                    :color="colors.interaction"
                  />
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
<!--  <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo" class="chat-iframe"></iframe>-->
<!--    </div>-->
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  min-height: 85vh;
}

.dashboard-content {
  animation: fade-in 0.3s ease-in-out;
}

@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

.login-required {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 70vh;
}

.user-info-card {
  margin-bottom: 20px;
}

.user-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stats {
  display: flex;
  gap: 40px;
  margin-top: 12px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 学伴按钮样式 */
.study-buddy-btn {
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  animation: pulse 2s infinite;
}

.study-buddy-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.icon-margin {
  margin-right: 8px;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
  }
  50% {
    box-shadow: 0 4px 20px rgba(103, 194, 58, 0.7);
  }
  100% {
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
  }
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.analysis-subtitle {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.course-list {
  height: 35vh;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
}

.scroll-container::-webkit-scrollbar {
  width: 6px;
  background-color: #f5f5f5;
}

.scroll-container::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.scroll-container::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

.course-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.course-item:hover {
  background-color: #f9f9f9;
}

.empty-courses, .empty-info {
  padding: 20px 0;
  color: #909399;
  text-align: center;
}

.course-info h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.class-info {
  height: 35vh;
}

.group-section {
  display: flex;
  gap: 30px;
}

.group-item {
  flex: 1;
}

.group-item h4 {
  margin-bottom: 12px;
  color: #666;
}

.group-link {
  display: block;
  margin-bottom: 8px;
  color: #409EFF;
  text-decoration: none;
}

.group-link:hover {
  text-decoration: underline;
}

.analysis-card {
  margin-top: 20px;
  height: 36vh;
}

.analysis-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px;
}

.analysis-item {
  text-align: center;
}

.chart-title {
  margin-bottom: 15px;
  font-weight: bold;
  color: #666;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
